import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { message } from 'antd';
import { DATA_ENTRY, AdvancedSearch, TableC, ContentPackage, PrimaryC } from '../../../comps';
import UpdateModalC from './updateModalC';
import myStyle from './index.less';
const FormItemLayout = {
  labelCol: {
    span: 6,
    offset: 0,
  },
  wrapperCol: {
    span: 18,
    offset: 0,
  },
};
@connect(({ bondInformationM, globalM, loading }) => ({
  bondInformationM,
  globalM,
  loading: loading.effects['bondInformationM/queryTableList'],
}))
export default class bondInformationC extends PureComponent {
  state = {
    columns: [],
    dataSource: [], //债券信息数据
    currentPage: 1, //当前页码
    numInPage: 10, //每页条数
    total: 0,
    searchObj: {
      begindTime: moment().subtract(1, 'months'),
      endTime: moment(),
    }, //查询条件
    selectProductList: [], //托管代销资格列表
    editObj: {}, //编辑信息
    visible: false, //模态框显示隐藏
    isEdit: '1', //默认为新增（1-新增  2-编辑   3-上市转换
    isReset: false, //是否点击重置
    sortedInfo: {},
    data: {},
    issuerList: [],
    unitList: [], // 期限单位
  };
  componentDidMount() {
    this.getTableData();
    this.props.dispatch({
      type: 'bondInformationM/getIssuerList',
      payload: {},
      callback: (data) => {
        if (data) {
          this.setState({
            issuerList: data,
          });
        } else {
          this.setState({
            issuerList: [],
          });
        }
      },
    });
    // 获取期限单位数据
    const {
      globalM: {
        dataDictionary: { COMPANY_DICT = [] },
      },
    } = this.props;
    this.setState({
      unitList: COMPANY_DICT,
    });
  }
  //获取表格数据
  getTableData = () => {
    const { dispatch } = this.props;
    const { searchObj, currentPage, numInPage, data } = this.state;
    const params = {
      issuerName: searchObj.issuerName ? searchObj.issuerName : '',
      tradingCode: searchObj.tradingCode ? searchObj.tradingCode : '',
      begindTime: searchObj.begindTime ? searchObj.begindTime.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
      endTime: searchObj.endTime ? searchObj.endTime.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
    };
    dispatch({
      type: 'bondInformationM/queryTableList',
      payload: {
        ...params,
        currentPage: currentPage,
        numInPage: numInPage,
        ...data,
      },
      callback: (status, data) => {
        if (status == 'success' && data) {
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            currentPage: data.pageInfo.currentPage,
            numInPage: data.pageInfo.numInPage,
            total: data.pageInfo.total,
          });
        }
      },
    });
  };

  // 新增模态框打开
  addModalOpen = () => {
    this.setState({
      visible: true,
      isEdit: 1,
    });
  };

  //修改模态框打开
  editAccount = (record) => {
    this.setState({
      visible: true,
      isEdit: 2,
      editObj: record,
    });
  };
  //上市转换模态框打开
  deTailAccount = (record) => {
    this.setState({
      visible: true,
      isEdit: 3,
      editObj: record,
    });
  };
  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
    });
  };

  //子组件调用父组件的getTableData方法
  useGetTableData = (msg) => {
    if (msg) {
      this.getTableData();
    }
  };
  // 删除债券发行信息
  deleteAccount = (record) => {
    this.props.dispatch({
      type: 'bondInformationM/deleteAccountById',
      payload: {
        id: record.id,
      },
      callback: (status) => {
        if (status == 'success') {
          this.getTableData();
        }
      },
    });
  };

  //表格页码排序改变调用
  handleTableChange = (pagination, filt, sorter) => {
    const { current, pageSize } = pagination;
    const data = {};
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    if (sorter.order !== undefined) {
      if (sorter.columnKey == 'tradingCode') {
        data.sort = 'trading';
      } else if (sorter.columnKey == 'secucategoryCodeiiName') {
        data.sort = 'secucategoryCodeii';
      } else {
        data.sort = sorter.columnKey;
      }

      if ('descend' == sorter.order) {
        data.sortType = 'desc';
      } else if ('ascend' == sorter.order) {
        data.sortType = 'asc';
      } else {
        delete data.sortType;
      }
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter,
        data: data,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 处理表格样式展示
  changeColumns = (columns) => {
    let data = columns;
    const { sortedInfo, unitList } = this.state;
    const {
      globalM: {
        dataDictionary: { Bond_Type_PBC = [], SUPPLEMENTARY_TOOL_DICT = [] },
      },
    } = this.props;
    if (data && data.length) {
      data.map((item) => {
        if (item.key == 'tradingCode') {
          // 债券代码
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'tradingCode' && sortedInfo.order;
        }
        if (item.key == 'secucategoryCodeiiName') {
          // 债券类型
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'secucategoryCodeiiName' && sortedInfo.order;
          item.render = (text, record) => {
            if (record.secucategoryCodeii === null || record.secucategoryCodeii === undefined) {
              return '--';
            } else {
              let findSelect = Bond_Type_PBC.filter((item) => item.code === record.secucategoryCodeii);
              return findSelect.length > 0 ? findSelect[0].value : '--';
            }
          };
        }
        if (item.key == 'couponRate') {
          // 利率
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'couponRate' && sortedInfo.order;
        }
        if (item.key == 'issuerName') {
          // 发行人
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'issuerName' && sortedInfo.order;
        }
        if (item.key == 'bondMaturity') {
          // 期限
          item.render = (text, record) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              let findSelect = unitList.filter((item) => item.code === record.termUnit);
              return findSelect.length > 0 ? text + findSelect[0].value : '--';
            }
          };
        }
        if (item.key == 'couponRate' || item.key == 'prepaindProp') {
          item.type = 'rate';
        }
        if (item.key === 'supplementaryTool') {
          item.render = (text, record) => {
            if (record.supplementaryTool === null || record.supplementaryTool === undefined) {
              return '--';
            } else {
              let findSelect = SUPPLEMENTARY_TOOL_DICT.filter((item) => item.code === record.supplementaryTool);
              return findSelect.length > 0 ? findSelect[0].value : '--';
            }
          };
        }
      });
    }

    return data;
  };

  showTable = () => {
    const { columns, dataSource, currentPage, numInPage, total } = this.state;
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editAccount(record);
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteAccount(record);
            },
          },
          {
            title: '上市转换',
            onClick: (record, index) => {
              this.deTailAccount(record);
            },
          },
        ],
      });
    }
    const columnss = this.changeColumns(columns);
    return (
      <div>
        <TableC
          columns={columnss}
          loading={this.props.loading}
          dataSource={dataSource}
          current={currentPage}
          pageSize={numInPage}
          total={total}
          scroll={{ x: 'max-content' }}
          rowKey='id'
          pagination={true}
          onChange={this.handleTableChange}
        />
      </div>
    );
  };

  //查询表格数据
  queryTableList = (e) => {
    this.setState(
      {
        dataSource: [],
        searchObj: e,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableData();
      },
    ); //查询之前清除数据
  };
  //获取发行人下拉列表
  getIssuerList = (e) => {
    if (!e) {
      this.props.dispatch({
        type: 'bondInformationM/getIssuerList',
        payload: {},
        callback: (data) => {
          if (data && JSON.stringify(data) != '{}') {
            this.setState({
              issuerList: data,
            });
          } else {
            this.setState({
              issuerList: [],
            });
          }
        },
      });
    } else {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        this.props.dispatch({
          type: 'bondInformationM/getIssuerList',
          payload: {
            name: e,
          },
          callback: (data) => {
            if (data && JSON.stringify(data) != '{}') {
              this.setState({
                issuerList: data,
              });
            } else {
              this.setState({
                issuerList: [],
              });
            }
          },
        });
      }, 500);
    }
  };
  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'tradingCode',
          title: '债券代码',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'issuerName',
          title: '发行人',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          filterOption: false,
          dataSource: this.state.issuerList,
          onSearch: (e) => this.getIssuerList(e),
        },
        {
          dataIndex: ['begindTime', 'endTime'],
          title: '发行区间',
          type: DATA_ENTRY.RANGEDATE,
          disableFuture: false,
          initialValue: [moment().subtract(1, 'months'), moment()],
          onRef: (ref) => {
            this.myData = ref;
          },
        },
      ],

      onQuery: (e) => {
        //点击查询按钮
        this.queryTableList(e);
      },

      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {
            begindTime: moment().subtract(1, 'months'),
            endTime: moment(),
          },
          isReset: true,
        });
        this.myData.reset();
      },
    };

    return (
      <ContentPackage
        title='债券发行维护'
        contentHtml={
          <div className={myStyle.splitPositionQuery}>
            <div className={'cardBody'}>
              <AdvancedSearch {...searchProps} />
            </div>
            <div>
              <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={this.addModalOpen} />
              {this.state.visible ? (
                <UpdateModalC
                  useGetTableData={this.useGetTableData}
                  editObj={this.state.editObj}
                  visible={this.state.visible}
                  changeVisible={this.changeVisible}
                  isEdit={this.state.isEdit}
                />
              ) : null}
            </div>
            <div>{this.showTable()}</div>
          </div>
        }
      />
    );
  }
}
